<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/14 0014
 * Time: 16:34
 */

namespace app\api\controller;

use app\common\logic\Logic;
use app\common\logic\UserId;
use app\common\model\Emoticon;
use app\common\model\Music;
use app\common\model\SkillApply;
use app\common\model\Users;
use Carbon\Carbon;
use think\Db;

class Api extends User
{


    /**
     * 获取融云token
     */
    public function token()
    {
        $token = $this->R_token($this->user_id);
        if ($token !== false) api_return(1, '获取成功', $token);
        api_return(0, '服务器繁忙,请稍后重试');
    }


    /**
     * 获取说明文档
     */
    public function explain()
    {
        $id = input('post.id');
        if (!is_numeric($id)) api_return(0, '参数错误');
        $data = Db::name('explain')->where('id', $id)->value('content');
        if (!empty($data)) api_return(1, '获取成功', $data);
        api_return(0, '暂无数据');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 客服列表
     */
    public function service()
    {
        $map['status']     = 1;
        $map['is_service'] = 1;
        $rows = Db::name('admins')->where($map)->field('user_id,nick_name,header_img')->select();

        foreach ($rows as $k => $v){
            $rows[$k]['user_id'] = 'admin'.hashid($v['user_id']);
        }

        api_return(1,'获取成功',$rows);

    }





    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 筛选分类下用户
     */
    public function screen()
    {

        $data  = input('post.');
        $map   = [];
        if ($this->getSex($this->user_id) == 1){
            $order = 'u.sex asc';
        }else{
            $order = 'u.sex desc';
        }

        $order .= ',e.online_status desc';

        //是否使用距离查询 默认false
        $distance = false;

        $map['a.status']  = 1;
        $map['a.is_use']  = 1;

        if (is_numeric($data['skill_id'])){
            $map['a.skill_id'] = $data['skill_id'];
            $map['f.skill_id'] = $data['skill_id'];
        }

        if ($data['grade']){
            $map['a.my_grade'] = ['in',$data['grade']];
        }

        if ($data['form_id']){
            $map['f.form_id'] = $data['form_id'];
        }

        if ($data['sex']){
            $map['u.sex'] = $data['sex'];
        }

        if ($data['section']){

            $time = ageDate($data['section']);
            $map['u.birthday'] = ['between time',$time];

        }



        switch ($data['order']){ //筛选条件

            case 'new': //新人

                $map['a.num'] = ['<=',3];

                break;
            case 'discount': //特惠
                // 特惠修改查询方式   价格字段已删除
                if ($this->getSex($this->user_id) == 1){
                    $order = 'u.sex asc,f.mini_price,e.online_status desc';
                }else{
                    $order = 'u.sex desc,f.mini_price,e.online_status desc';
                }
                break;
            case 'score': //根据好评排序 评分

                $order = 'a.score desc';

                break;
            case 'online':

//                $order .= ',e.online_status desc';
//                $map['e.online_status'] = 1;

                break;
            case 'city': //同城查询 根据距离查询
                if ($this->getSex($this->user_id) == 1){
                    $order = 'u.sex asc,distance';
                }else{
                    $order = 'u.sex desc,distance';
                }
                $distance = true;

                break;
            default://热门

                $order .= ',a.num desc,a.score desc,e.online_status desc';

                break;
        }

//        $map['a.user_id'] = ['neq',$this->user_id];

        $model = new SkillApply();
        if ($distance){
//            $rows = $model->getCity($map,$this->userExtra('log,lat'),$this->extend('distance'),$order);
            if (isset($map['a.skill_id'])){
                //存在技能id  查询技能下同城
                $rows = $model->getCity($map,$this->userExtra('log,lat'),$this->extend('distance'),$order);
            }else{
                //不存在技能id 单独查询
                $rows = (new Users())->getCity($map,$this->extend('distance'),$order,$this->userExtra('log,lat'));
            }



//            $rows = (new Users())->search([],$this->user_id,true,$this->userExtra('log,lat'));


//                $map['a.user_id'] = ['neq',$this->user_id];

        }else{
//            $map['a.user_id'] = ['neq',$this->user_id];
            $rows  = $model->getUsers($map,$order,$this->user_id);

        }

        api_return(1,'获取成功',$rows);

    }





    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 颜值筛选
     */
    public function vod()
    {

        $map = [];
        $map['a.status'] = 1;

        $model = new \app\common\model\Vod();

        $rows = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户搜索
     */
    public function search()
    {


        $map = [];

        $data = input('post.');

        if ($data['nick_name']){

            $map['a.nick_name|a.uuid'] = ['like','%'.trim($data['nick_name']).'%'];

        }

        if ($data['section']){

            $time = ageDate($data['section']);
            $map['a.birthday'] = ['between time',$time];

        }

        if ($data['sex']){

            $map['a.sex'] = $data['sex'];

        }

        $map['a.user_id'] = ['neq',$this->user_id];

        $model = new Users();
        if ($data['city'] == 'distance'){
            //查询同城
            $rows = $model->search($map,$this->user_id,true,$this->userExtra('log,lat'));
        }else{
            $rows = $model->search($map,$this->user_id);
        }

        api_return(1,'获取成功',$rows);

    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户贵族等级
     */
    public function noble()
    {
        $data['noble'] = $this->userExtra('noble_id,noble_time,user_id');
        // 判断是否需要使用checkNoble方法更新用户的贵族等级
        $data['rows']  = Db::name('noble')->field('create_time,update_time',true)->order('noble_id')->select();


        if (input('from_type') == 'up'){
            $data['rows'][0]['price'] = 1048;
            $data['rows'][1]['price'] = 2998;
            $data['rows'][2]['price'] = 6498;
            $array[] = $data['rows'][0];
            $data['rows'] = $array;

        }


        $data['noble']['noble_id'] = self::checkNoble($data['noble']);

        if ($data['noble']['noble_time'] > time()){
            $str = '到期';
        }else{
            $str = '已过期';
        }
        $data['noble']['user_id'] = hashid($data['noble']['user_id']);
        $data['tips'] = self::extend('explain');

        Carbon::setLocale('zh');

        $data['noble']['noble_time'] = Carbon::createFromTimestamp($data['noble']['noble_time'])->diffForHumans().$str;
        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 身份认证提交页面
     */
    public function checkView()
    {
        api_return(1,'获取成功',$this->extend('check_explain,face_example,back_example,self_example'));
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 身份认证
     */
    public function check()
    {

        $data = request()->only(['real_name','ID_num','face','back','img'],'post');

        if ($this->userInfo('ID')) api_return(0,'您已实名认证,请勿重复操作');

        $map['user_id'] = $this->user_id;

        $model = new UserId();

        $item = $model->where($map)->find();
        $data['status'] = 3;

        if ($item){

            if ($item['status'] == 3) api_return(0,'您的身份认证正在审核中,请稍后重试');

            $this->checkId($data);

            $result = $item->validate(true)->save($data);
            if (!$result){
                api_return(0,$item->getError());
            }
        }else{

            $this->checkId($data);

            $data['user_id'] = $this->user_id;

            $result = $model->saveChange($data);
        }

        if ($result) api_return(1,'提交成功,请耐心等待管理员审核');
        api_return(0,$model->getError());
    }

    /**
     * 验证身份证
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    protected function checkId($data){
        if (self::getExplain('openIdCheck') == 'open'){
            if (empty($data['real_name'])){
                api_return(0,'请输入真实姓名');
            }

            $check = IDCard($data['ID_num']);

            if ($check !== true){
                api_return(0,$check);
            }
            $url = sprintf( 'http://op.juhe.cn/idcard/query?key=%s&idcard=%s&realname=%s',config('juhe.IDkey'),$data['ID_num'],$data['real_name']);
            $row = curl_get($url);
            if ($row['error_code'] === 0  ){
                if ($row['result']['res'] != 1){
                    api_return(0,'身份证号码与姓名不匹配');
                }
            }else{
                api_return(0,'身份证号码与真实姓名验证错误');
            }
        }
        return true;
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 举报用户或房间
     */
    public function report()
    {
        $this->ApiLimit(60,$this->user_id,'每分钟只能举报一次!');

        $data = request()->only(['type','id','reason','imgs'],'post');

        if ($data['type'] == 2) $data['id'] = dehashid($data['id']);

        if (!is_numeric($data['id'])) api_return(0,'参数错误');

        if ($data['type'] == 2){
            if (empty($data['reason'])) api_return(0,'举报理由不能为空');
        }

        $data['user_id'] = $this->user_id;

        $logic = new Logic();
        $logic->changeTable('reason');
        $result = $logic->save($data);

        if ($result){
            api_return(1,'举报成功');
        }else{
            api_return(0,'系统繁忙,请稍后重试');
        }
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取表情包
     */
    public function getEmoticon()
    {
        $model = new Emoticon();

        $rows  = $model->getEmoticonList();

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据用户id获取头像及昵称
     */
    public function getUserInfo()
    {
        $id = input('post.id');
        if ($id){
            $user_id = dehashid($id);
        }else{
            $user_id = $this->user_id;
        }
        $data = $this->userInfo('nick_name,user_id,header_img',$user_id);

        $data['user_id'] = hashid($data['user_id']);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天列表多人查询
     */
    public function usersInfo()
    {

        $ids = input('post.ids');
        if (!$ids){
            api_return(0,'参数错误');
        }

        $ids = explode(',',$ids);
        $ids = array_unique($ids);
        $arr = [];
        //循环解密要查询的用户id
        foreach ($ids as $k => $v){
            $id = dehashid($v);
            if ($id){
                $arr[] = $id;
            }
        }

        if (empty($arr)){
            api_return(0,'参数错误');
        }

        if (count($arr) == 1){
            //只查询一个用户   不要用in方法
            $map['a.user_id'] = $arr[0];
            $rows[] = Db::name('users')->alias('a')->where($map)
                ->join('user_extend e','e.user_id = a.user_id','LEFT')
                ->join('room r','r.room_id = e.room_id','left')
                ->field('a.nick_name,a.header_img,a.user_id,e.room_id,r.img,r.is_lock,r.password')
                ->cache(15)
                ->find();
        }else{
            $map['a.user_id'] = ['in',$arr];
            $rows = Db::name('users')->alias('a')->where($map)
                ->join('user_extend e','e.user_id = a.user_id','LEFT')
                ->join('room r','r.room_id = e.room_id','left')
                ->field('a.nick_name,a.header_img,a.user_id,e.room_id,r.img,r.is_lock,r.password')
                ->cache(3)
                ->select();
        }

        $map['a.status']  = 1;


        foreach ($rows as $k => $v){
            //不在房间中给出默认数据 防止前端崩溃
            if ($v['room_id'] == 0){
                $rows[$k]['img']      = '';
                $rows[$k]['password'] = '';
                $rows[$k]['is_lock']  = 0;
                $rows[$k]['power']    = 1;
            }else{
                $rows[$k]['power'] = getPowerCode($this->user_id,$v['room_id']);
            }
            $rows[$k]['user_id'] = hashid($v['user_id']);
        }

        api_return(1,'获取成功',$rows);

    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据群组id获取头像及昵称
     */
    public function getGroupInfo(int $id)
    {
        $data = Db::name('chat_group')->where('group_id',$id)->field('group_id,group_name,img')->find();
        api_return(1,'获取成功',$data);
    }

    /**
     * 获取音乐列表
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function musicList()
    {
        $model = new Music();

        if (!empty(input('keyword'))){
            $map['song_name|singer'] = ['like','%'.trim(input('keyword')).'%'];
        }

        $map['status'] = 1;

        $rows = $model->getList($map);

        api_return(1,'获取成功',$rows);

    }

    


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 系统管理员头像等信息
     */
    public function sysInfo()
    {
        $id = input('post.id');

        if (strstr($id,"admin")){ //客服信息查询
            $user_id = dehashid(str_replace('admin','',$id));
            if (is_numeric($user_id)){
                $map['user_id'] = $user_id;
                $map['is_service'] = 1;
                $info = Db::name('admins')->where($map)->field('nick_name,header_img')->find();
                if ($info){
                    goto success;
                }
            }
            goto error;
        }

        //判断要获取信息的id  特殊id单独处理
        switch ($id){
            case 'system':
                $info['nick_name']  = '系统管理员';
                $info['header_img'] = $this->extend('sys_header_img');
                break;
            case 'sysOrder':
                $info['nick_name']  = '抢单消息';
                $info['header_img'] = 'http://file.mengpaxing.com/order.png';
                break;
            case 'sysCustomer':
                $info['nick_name']  = '小助手';
                $info['header_img'] = $this->extend('sys_header_img');
                break;
            default:
                goto error;
                break;
        }

        success:
        $info['user_id'] = $id;
        api_return(1,'获取成功',$info);

        error:
        api_return(0,'非法参数');
    }

    /**
     * 苹果内购验证
     */
    public function orderCheck($apple_receipt)
    {
        if (empty($apple_receipt)) api_return(0,'参数错误');
        //测试地址
        $url = 'https://sandbox.itunes.apple.com/verifyReceipt';
//        $url = 'https://buy.itunes.apple.com/verifyReceipt';

        $check = Db::name('apple_pay')->where('apple_receipt',$apple_receipt)->value('id');

        if ($check){
            api_return(0,'该订单已充值!');
        }

        $json = $this->http_post($url,$apple_receipt);

        //两次操作将返回的对象转换为数组
        $data = json_decode(json_encode($json),true);

        if ($data['status'] === 0 ){
            $row = $data['receipt']['in_app'][0]['product_id'];
            $price = explode('_',$row)[1];

            $noble = ['vip1','vip2','vip3'];

            if (in_array($price,$noble)){//内购购买贵族
                switch ($price){
                    case 'vip1':
                        $vip = 1;
                        break;
                    case 'vip2':
                        $vip = 2;
                        break;
                    case 'vip3':
                        $vip = 3;
                        break;
                    default:
                        api_return(0,'内购参数错误');
                }
                
                $body = Db::name('noble')->where('noble_id',$vip)->find();

                $body['user_id'] = hashid($this->user_id);
                if ($this->nobles($body)){
                    $this->addLevel($data['price'],$this->user_id);
                }

                api_return(1,'购买成功');

            }else{
                if (!is_numeric($price)) api_return(0,'非法参数');

                $data = Db::name('users')->where('user_id',$this->user_id)->setInc('money',$price);

                $item['user_id']     = $this->user_id;
                $item['money']       = $price;
                $item['remark']      = '伴心'.$price.'钻充值';
                $item['status']      = 1;
                $item['type']        = 1;
                $item['create_time'] = time();
                $item['update_time'] = time();
                $item['trade_type']  = 3;

                Db::name('bankroll')->strict(false)->insert($item);

                if ($data){
                    //砸蛋活动开启时赠送锤子
                    $info = self::getExplain('giveOpen,givePrice');
                    if ($info['giveOpen'] === 'open'){
                        $num = bcdiv($price,$info['givePrice'],0);
                        //查询是否为首次充值
                        $con['user_id'] = $this->user_id;
                        $con['type']    = 1;
                        $first = Db::name('bankroll')->where($con)->count();
                        if ($first == 0){
                            if ($num > 0){
                                Db::name('users')->where('user_id',$this->user_id)->setInc('hammer_give');
                                $str = '首次充值赠送了1个锤子,赶快进入砸蛋活动使用吧!';
                                self::sendUsrMsg('system',hashid($this->user_id),$str);
                            }
                        }
                    }
                    $map['user_id'] = $this->user_id;
                    $map['apple_receipt'] = $apple_receipt;
                    Db::name('apple_pay')->insert($map);
                    api_return(1,'充值成功');
                }
            }
        }
        api_return(0,'充值失败');
    }

    //curl请求苹果app_store验证地址
    public function http_post($url, $data_string) {
        $curl_handle=curl_init();
        curl_setopt($curl_handle,CURLOPT_URL, $url);
        curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle,CURLOPT_HEADER, 0);
        curl_setopt($curl_handle,CURLOPT_POST, true);
        curl_setopt($curl_handle,CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER, 0);
        $response_json = curl_exec($curl_handle);
        $response = json_decode($response_json);
        curl_close($curl_handle);
        return $response;
    }


    /**
     * 查询用户在房间的权限以及是否需要输密码
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function roomCheck()
    {
        $id = input('room_id');
        if (!is_numeric($id)){
            api_return(0,'房间id错误');
        }
        $data = Db::name('room')->where('room_id',$id)->field('is_lock,password')->find();
        $data['power'] = getPowerCode($this->user_id,$id);
        api_return(1,'获取成功',$data);
    }



}